import { computed } from 'vue'

/**
 * 生成月度范围集合的Hook
 * @param {object} options - 配置项
 * @param {number} [options.startYear] - 起始年份
 * @param {number} [options.startMonth] - 起始月份 (1-12)
 * @param {Date} [options.endDate] - 截止日期（默认当前日期）
 * @param {boolean} [options.chineseFormat] - 是否使用中文格式（默认true）
 * @returns {object} { months, monthOptions, currentMonth }
 */
export default function useMonthlyRanges(options = {}) {
    const {
        startYear = 2023,
        startMonth = 1,
        endDate = new Date(),
        chineseFormat = true,
    } = options

    // 主计算逻辑
    const months = computed(() => {
        const result = []
        const currentDate = new Date(startYear, startMonth - 1, 1)
        const endYear = endDate.getFullYear()
        const endMonth = endDate.getMonth() + 1

        while (
            currentDate.getFullYear() < endYear
            || (currentDate.getFullYear() === endYear && currentDate.getMonth() + 1 <= endMonth)
        ) {
            const year = currentDate.getFullYear()
            // const month = currentDate.getMonth() // 获取上一月
            const month = currentDate.getMonth() + 1 // 获取当前月份
            const firstDay = new Date(year, month - 1, 1)
            const lastDay = new Date(year, month, 0)

            result.push({
                label: chineseFormat
                    ? `${year}年${String(month).padStart(2, '0')}月`
                    : `${year}-${String(month).padStart(2, '0')}`,
                start: formatDate(firstDay),
                end: formatDate(lastDay),
                value: `${year}${String(month).padStart(2, '0')}`,
            })

            currentDate.setMonth(currentDate.getMonth() + 1)
        }
        const monthRangs = result
        return monthRangs.slice(0, monthRangs.length - 1).reverse()
        // return result
    })

    // 下拉框专用选项
    const monthOptions = computed(() =>
        months.value.map(m => ({ label: m.label, value: m.value })),
    )

    // 当前月份信息
    const currentMonth = computed(() => {
        const now = new Date()
        const year = now.getFullYear()
        const month = now.getMonth() + 1
        return {
            label: chineseFormat
                ? `${year}年${String(month).padStart(2, '0')}月`
                : `${year}-${String(month).padStart(2, '0')}`,
            value: `${year}-${String(month).padStart(2, '0')}`,
        }
    })

    return { months, monthOptions, currentMonth }
}

// 辅助函数：格式化日期
function formatDate(date) {
    return date.toISOString().split('T')[0] // YYYY-MM-DD
}

// 辅助函数：格式化日期
function formatDate2(date) {
    return date.toISOString().split('T')[0].replaceAll('-', '') // YYYYMM
}
